import pymysql

connection = None
cursor = None

try:
    connection = pymysql.connect(host="localhost", port=3306, user="root",passwd="<PASSWORD>",database="test", charset="utf8")
    cursor = connection.cursor()
    # 其中 %s 是参数的占位符，不是字符串格式化，而是数据库操作库提供的参数化查询机制。
    values = (1, "python从入门到大成", "2025-01-01")
    cursor.execute("insert into t_book(id, title, pud_date) values (%s, %s, %s);" ,values)
    # 查看 sql执行，影响多少行
    print("影响的行数：", connection.affected_rows())
    # 提交事务
    connection.commit()
except Exception as e:
    print(e)
    connection.rollback()
finally:
    cursor.close()
    connection.close()
    cursor = None
    connection = None

